package com.leyou.service.impl;

import com.leyou.constants.JwtConstants;
import com.leyou.constants.RedisConstants;
import com.leyou.dto.Payload;
import com.leyou.dto.UserDTO;
import com.leyou.dto.UserDetails;
import com.leyou.myException.LyException;
import com.leyou.service.UserLoginService;
import com.leyou.user.client.UserClient;
import com.leyou.utils.CookieUtils;
import com.leyou.utils.JwtUtil;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author jshstart
 * @creat 2020-12-23 15:47
 */
@Service
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 实现用户登录
     * @param username
     * @param password
     * @param response
     */
    @Override
    public void userLogin(String username, String password, HttpServletResponse response) {
        try {
            //1.调用user微服务，查询到用户
            UserDTO userDTO = userClient.queryUserByNamePassword(username, password);
            //2.匹配

            if (userDTO==null){
                throw new LyException(400,"用户名或者密码错误");
            }
            //3.如果正确，生成jwt
            String userJwt = jwtUtil.createJwt(UserDetails.of(userDTO.getId(), userDTO.getUsername()));
            //4.写入cookie
            addCookie(response,userJwt);
        } catch (FeignException e) {
            throw new LyException(e.status(),e.contentUTF8());
        }
    }

    /**
     * 退出时删除用户的cookie和在redis中的jti
     * @param request
     * @param response
     */
    @Override
    public void userLogout(HttpServletRequest request, HttpServletResponse response) {
        String jwt = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
        Payload payload = null;
        try {
            payload = jwtUtil.parseJwt(jwt);
        } catch (Exception e) {
            //如果为空就返回，不处理
            return;
        }
        UserDetails userDetail = payload.getUserDetail();
        //删除redis中的jti
        redisTemplate.delete(RedisConstants.JTI_KEY_PREFIX+userDetail.getId());
        //删除cookie
        CookieUtils.deleteCookie(JwtConstants.COOKIE_NAME,JwtConstants.DOMAIN,response);
    }

    private void addCookie(HttpServletResponse response, String userJwt) {
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, userJwt);
        //cookie的作用范围
        cookie.setPath("/");
        //cookie的作用域
        cookie.setDomain(JwtConstants.DOMAIN);
        //是否禁止js操作cookie，避免xss攻击
        cookie.setHttpOnly(true);
        //cookie的生命周期，默认是-1，即本次会话，浏览器关闭就会消失
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
    }
}
